<template>
  <div class="container app-container">
    <div
      class="title"
      style="
        margin: 20px 0 20px 0;
        height: 20px;
        line-height: 20px;
        border-left: 1px solid #ccc;
        text-indent: 15px;
      "
    >
      基本信息
    </div>

    <div class="form">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="归属企业" prop="companyId">
              <el-select
                v-model="form.companyId"
                filterable
                placeholder="请选择"
                @change="handleShipQuery"
              >
                <el-option
                  v-for="dict in companyList"
                  :key="dict.id"
                  :label="dict.companyNickName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="船舶信息" prop="shipId">
              <el-select v-model="form.shipId" filterable placeholder="请选择">
                <el-option
                  v-for="dict in shipDataList"
                  :key="dict.id"
                  :label="dict.shipName"
                  :value="dict.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="空船港" prop="originPortName">
              <el-select v-model="form.originPortName" filterable placeholder="请选择">
                <el-option
                  v-for="dict in portList"
                  :key="dict.enName"
                  :label="dict.enName"
                  :value="dict.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="目的港" prop="destPortNames">
              <el-select v-model="form.destPortNames" filterable placeholder="请选择" multiple>
                <el-option
                  v-for="dict in portList"
                  :key="dict.enName"
                  :label="dict.enName"
                  :value="dict.name"
                />
              </el-select>
              <span style=" color: #ccc; font-size: 14px"> 多选，可添加目的地 </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="可放空点" prop="pointNames">
              <el-select v-model="form.pointNames" filterable placeholder="请选择" multiple>
                <el-option
                  v-for="dict in portList"
                  :key="dict.enName"
                  :label="dict.enName"
                  :value="dict.name"
                />
              </el-select>
              <span style=" margin: 0 0 -20px 5px; color: #ccc; font-size: 14px">选填，多选，可添加途径空船地点 </span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="20">
            <el-col :span="6">
              <el-form-item label="空船日期" prop="originDate">
                <el-date-picker
                  v-model="form.originDate"
                  type="date"
                  placeholder="选择日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="1" style="line-height: 32px; text-align: center">±</el-col>
            <el-col :span="2">
              <el-input v-model="form.floatingDays" placeholder="天" />
            </el-col>
          </el-col>
        </el-row>

        <el-form-item label="运输类型" prop="transportType">
          <el-select
            v-model="form.transportType"
            placeholder="运输类型"
            clearable
            style="width: 220px"
          >
            <el-option
              v-for="dict in dict.type.sys_transport_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <!-- 表单项放这里 -->
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人" prop="contacts">
              <el-input
                v-model="form.contacts"
                placeholder="请输入"
                maxlength="10"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人手机号" prop="contactPhone">
              <el-input
                v-model="form.contactPhone"
                placeholder="请输入"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input
                style="width: 500px"
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                maxlength="500"
                size="medium"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="footer">
      <el-button size="mini" type="primary" @click="submitForm" class="submit-btn" v-preventReClick
        >确认保存</el-button
      >
    </div>
  </div>
</template>

<script>
// 导入接口方法
import { getCompanyList, getShipListByCompany, getPortList } from '@/api/common/index';
import { addShipOrder, editShipOrder, getOrderShipDetail } from '@/api/orders/orderShip';

export default {
  // 要改命名，比如课程编辑页可以叫 courseAddOrUpdate
  name: 'CourseAddOrUpdate',
  dicts: ['sys_transport_type'],
  components: {},
  data() {
    return {
      // 标题
      title: '',
      // 初始化 id 为 null
      id: null,
      // 初始化 isEdit 为 false
      isEdit: false,
      // 表单参数
      form: {
        type: this.$route.params.type != null ? this.$route.params.type : null,
        companyId: null,
        shipId: null,
        originPortName: '',
        originDate: null,
        transportType: null,
        floatingDays: 0,
        destPortNames: [],
        pointNames: [],
        contacts: '',
        contactPhone: '',
        remark: '',
      },
      companyList: [],
      shipDataList: [],
      portList: [],
      // 表单校验
      rules: {
        companyId: [{ required: true, message: '归属企业不能为空', trigger: 'blur' }],
        shipId: [{ required: true, message: '船舶不能为空', trigger: 'blur' }],
        contacts: [{ required: true, message: '联系人不能为空', trigger: 'blur' }],
        contactPhone: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
      },
    };
  },
  created() {
    // 通过 $route.params 获取路由参数
    this.id = this.$route.query.id ? this.$route.query.id : null;
    // 判断是否存在 id 参数
    this.isEdit = !!this.id;
    if (this.isEdit) {
      // 如果存在 id 参数，则说明当前页面是修改状态
      // 可以根据 id 参数获取需要修改的数据
      this.getOrderShipDetail(this.id);
    } else {
      // 如果不存在 id 参数，则说明当前页面是新增状态
    }
  },
  mounted() {
    this.handlePortsQuery();
    this.handleCompanyQuery();
  },
  methods: {
    // 表单重置
    reset() {
      this.form = {
        companyId: null,
        shipId: null,
        originPortName: '',
        originDate: null,
        transportType: null,
        floatingDays: 0,
        destPortNames: [],
        pointNames: [],
        contacts: '',
        contactPhone: '',
        remark: '',
      };
      this.resetForm('form');
    },

    // 获取港口
    handlePortsQuery() {
      getPortList().then((res) => {
        this.portList = res.data;
      });
    },

    // 获取船舶
    handleShipQuery() {
      getShipListByCompany(this.form.companyId).then((res) => {
        this.shipDataList = res.data;
        // 确保在获取船舶列表后，根据form.shipId选中对应的船舶
        if (this.form.shipId && this.shipDataList.length > 0) {
          const matchedShip = this.shipDataList.find((item) => {
            if (item.id == this.form.shipId) {
              return item;
            }
          });
          // 如果找到匹配的船舶，则保持选中状态
          if (matchedShip) {
            this.form.shipId = matchedShip.id;
          } else {
            // 如果没找到，则清除已选中的船舶ID
            this.form.shipId = null;
          }
        }
      });
    },

    // 获取企业
    handleCompanyQuery() {
      getCompanyList().then((res) => {
        this.companyList = res.data;
      });
    },

    /** 获取form表单数据 */
    async getOrderShipDetail(id) {
      try {
        const res = await getOrderShipDetail(id);
        if (res.code == 200) {
          const {
            companyId,
            shipId,
            originPortName,
            originDate,
            transportType,
            floatingDays,
            destPortNames,
            pointNames,
            contacts,
            contactPhone,
            remark,
          } = res.data;

          this.form = {
            companyId,
            shipId,
            originPortName,
            originDate,
            transportType,
            floatingDays,
            destPortNames: destPortNames.split(','),
            pointNames: pointNames.split(','),
            contacts,
            contactPhone,
            remark,
          };
          // 在获取订单船舶详情成功后，触发根据公司ID获取船舶列表的操作
          if (companyId) {
            this.form.companyId = companyId;
            this.handleShipQuery(companyId); // 传递正确的companyId
          }
        }
      } catch (err) {
        console.error(err);
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.id != null) {
            this.$confirm('确定修改当前内容', '确定保存', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用修改接口
                this.handleUpdate();
              })
              .catch(() => {});
          } else {
            this.$confirm('确定发布', '确定发布', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用新增接口
                this.handleAdd();
              })
              .catch(() => {});
          }
        }
      });
    },

    /** 新增 */
    handleAdd() {
      let saveData = {
        ...this.form,
      };
      // 预处理接口传参
      saveData.destPortNames = saveData.destPortNames.join(',');
      saveData.pointNames = saveData.pointNames.join(',');
      // saveData.trainTypeIds = saveData.trainTypeIds.join(',');
      // saveData.thumbnailUrl = process.env.VUE_APP_IMG_PRE + saveData.thumbnailUrl;
      this.$modal.loading('正在保存...');

      addShipOrder(saveData)
        .then((res) => {
          if (res.code == 200) {
            this.close();
          } else {
            this.$message.error(res.message);
          }
          this.$modal.closeLoading();
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },

    /** 更新 */
    handleUpdate() {
      let saveData = {
        ...this.form,
      };
      // 预处理接口传参
      saveData.id = this.id;
      saveData.destPortNames = saveData.destPortNames.join(',');
      saveData.pointNames = saveData.pointNames.join(',');
      this.$modal.loading('正在保存...');

      editShipOrder(saveData)
        .then((res) => {
          if (res.code == 200) {
            this.close();
          }
          this.$modal.closeLoading();
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },

    /** 关闭按钮 */
    close() {
      // 跳转地址 和 携带参数
      const obj = {
        path: '/orders/ship/list',
        query: {
          t: Date.now(),
          pageNum: this.$route.query.pageNum,
        },
      };
      this.$tab.closeOpenPage(obj).then(() => {
        this.$tab.refreshPage(obj);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
}

.submit-btn {
  position: fixed;
  bottom: 10px;
  left: 50%;
}
</style>
